package com.example.sdk.filter;


import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by mobao-xi on 16/3/17.
 */
public class EncryptServletResponse extends HttpServletResponseWrapper {


    private MyOutStream myOutStream;

    public boolean needCompress = false;

    public EncryptServletResponse(HttpServletResponse httpServletResponse) {
        super(httpServletResponse);
        try {
            myOutStream = new MyOutStream(httpServletResponse.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void finalize() throws Throwable {
        super.finalize();
    }

    public synchronized byte[] getContent() {
        try {
            byte[] s = myOutStream.myOutput.toByteArray();
            return s;
        } catch (Exception e) {
            e.printStackTrace();
            return "UnsupportedEncoding".getBytes();
        }
    }

    public synchronized void output(String result) throws IOException {
        this.output(result.getBytes());
    }

    public synchronized void output(byte[] data) throws IOException {
        // 压缩返回结果
        byte[] out = null;
//        if (needCompress) {
//            out = ZipUtil.compress(data, GZipOutputStream.TYPE_GZIP);
//        }
        if (out != null) {
            // 返回结果已被压缩
            this.setContentType("application/x-gzip;charset=UTF-8");
            // 客户端据此判断内容是否需要解压缩
            this.setHeader("Content-Encoding", "gzip");
        } else {
            out = data;
        }
        // 发送返回结果
        OutputStream output = myOutStream.stream;
        this.setContentLength(out.length);
        output.write(out);
        output.flush();
        output.close();
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return myOutStream;
    }


    public void close() throws IOException {
        myOutStream.close();
    }


    private static class MyOutStream extends ServletOutputStream {
        ServletOutputStream stream;

        ByteArrayOutputStream myOutput;

        public MyOutStream(ServletOutputStream stream) {
            this.stream = stream;
            myOutput = new ByteArrayOutputStream();
        }

        @Override
        public void write(int b) throws IOException {
            myOutput.write(b);
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {

        }
    }
}
